<?php

class RaiseTable extends RaiseUIControl {

    /**
     * The data to use for the control to populate
     * @var object
     */
    private $data;
    
    public function data($data = null){
        if(func_num_args() == 1){
            $this->data = $data;
        }
        return $this->data;
    }
    
    public function output() {
        $repeater = new RaiseRepeater();
        $columns = new RaiseCollection();
        $data = $this->data;
        if(is_object($data) && !($data instanceof RaiseCollection)){
            $data = new RaiseCollection((array)$data);
        }
        if($this->data instanceof RaiseCollection){
            if($this->data->isSequential()){
                $iterator = $this->data->iterator();
                while ($iter = $iterator->iterate()){
                    foreach($iter->value() as $k => $v){
                        if(!$columns->keyExists($k)){
                            $columns->add($k, $v);
                        }
                    }
                }
            }else{
                foreach($this->data as $k => $v){
                    if(!$columns->keyExists($k)){
                        $columns->add($k, $v);
                    }
                }
                $data = array($data);
            }
        }
        $formatters = array();
        $headers = '<tr>';
        $sTemplate = '<tr>';
        foreach($columns as $c => $v){
            $headers .= '<th>' . $c . '</th>';
            $sTemplate .= '<td>{' . $c . '}</td>';
            if($v instanceof RaiseDateTime){
                $formatters[$c] = new RaiseDateTimeFormatter(RaiseDateTimeFormatter::ISO8601);
            }
        }
        $sTemplate .= '</tr>';
        $headers .= '</tr>';
        $template = new RaiseTemplate($sTemplate);
        foreach($formatters as $k => $f){
            $template->fieldFormat()->add($k, $f);
        }
        $repeater->template($template);
        $repeater->data($data);
        return '<table>' . $headers . $repeater->output() . '</table>';
    }
    
}